package com.my.controal;

import java.sql.*;

public class JDBC {

    Connection conn;
    Statement stmt;

    // 单例
    private static JDBC instance;

    public static JDBC Instance() {
        if (instance == null) {
            instance  = new JDBC();
        }
        return instance;
    }

    // 构造方法
    public JDBC() {
        connectMysql("jdbc:mysql://Localhost:3306/db_trian?serverTimezone=UTC", "root", "aquaman");
    }

    // 链接数据库
    private void connectMysql(String url, String username, String password) {

        try {
            // 驱动注册
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 创建连接器
            conn = DriverManager.getConnection(url, username, password);
            // 创建执行对象
            stmt = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 查询
    public ResultSet selectTable(String sql) throws SQLException {

        ResultSet rs = stmt.executeQuery(sql);
        System.out.println("success");

        return rs;
    }

    // 增删改
    public void querySQLCommand(String sql) throws SQLException {
        stmt.addBatch(sql);
        stmt.executeBatch();
    }

    // 关闭
    public void closeMysql() throws SQLException {
        conn.close();
        stmt.close();
    }
}
